package cn.rainshare.controller;

import cn.rainshare.entity.Student;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class MyController {

    @RequestMapping(value = {"/register.do"})
    public ModelAndView register(Student student){

        ModelAndView mv = new ModelAndView();
        System.out.println(student);
        mv.addObject("id",student.getId());
        mv.addObject("name",student.getName());
        mv.addObject("msg","注册成功");

        mv.setViewName("success");

        return mv;
    }


    @RequestMapping("/returningString.do")
    @ResponseBody
    public String returningString(Integer id, String name){

        return "this is data or view 测试";
    }


    @RequestMapping(value = "/returningVoid-ajax.do")
    public void ReturningVoid(HttpServletResponse response,
                              Integer id,String name) throws Exception{

        System.out.println(id);
        System.out.println(name);
        Student stu = new Student(id, name);
        String json = "";
        ObjectMapper objectMapper = new ObjectMapper();
        json= objectMapper.writeValueAsString(stu);
        System.out.println(json);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter pr = response.getWriter();
        pr.print(json);
        pr.flush();
        pr.close();

    }

    @RequestMapping(value = "/returningStu-ajax.do")
    @ResponseBody
    public Map<String,List<Student>> ReturningStu(Integer id, String name) {

        System.out.println(id);
        System.out.println(name);
        Student stu1 = new Student(id, name);
        Student stu2 = new Student(1001, "李四");
        Student stu3 = new Student(1002, "王五");

        List<Student> students = new ArrayList<>();

        students.add(stu1);
        students.add(stu2);
        students.add(stu3);

        Map<String,List<Student>> map = new HashMap<>();

        map.put("key",students);

        return map;

    }
}
